package com.study.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.enums.HttpStatusEnum;
import com.study.mapper.StudentMapper;
import com.study.model.dto.StudentQueryDTO;
import com.study.model.entity.StudentDO;
import com.study.model.vo.PageVO;
import com.study.result.AjaxResult;
import com.study.service.IStudentService;
import com.study.utils.JsonUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
public class StudentServiceImpl implements IStudentService {

    @Resource
    private StudentMapper studentMapper;


    @Override
    public AjaxResult selectStudentById(Long id) {
        StudentDO studentDO = studentMapper.selectStudentById(id);
        if (studentDO == null) {
            return AjaxResult.fail(HttpStatusEnum.RESOURCE_NOT_FOUND.getCode(), HttpStatusEnum.RESOURCE_NOT_FOUND.getMsg());
        }
        return AjaxResult.success(studentDO);
    }

    @Override
    public AjaxResult selectStudentList(StudentQueryDTO studentQueryDTO) {
        Page<StudentDO> page;
        if (studentQueryDTO.getPageNum()==null || studentQueryDTO.getPageSize()==null) {
            page = PageHelper.startPage(1, 10);
        } else {
            page = PageHelper.startPage(studentQueryDTO.getPageNum(), studentQueryDTO.getPageSize());
        }
        List<StudentDO> list = studentMapper.selectStudentList(studentQueryDTO);
        return AjaxResult.success(PageVO.getPageVO(page, list));
    }

    @Override
    public AjaxResult insertStudent(StudentDO studentDO) {
        if (JsonUtil.isNotValidJsonStr(studentDO.getConfigJson())) {
            return AjaxResult.fail("格式不是合法JSON字符，请重新输入。");
        }
        studentDO.setCreateTime(new Date());
        studentDO.setUpdateTime(new Date());
        return AjaxResult.toAjax(studentMapper.insertStudent(studentDO));
    }

    @Override
    public AjaxResult updateStudent(StudentDO studentDO) {
        if (studentDO.getId()==null) {
            return AjaxResult.fail("ID不能为空");
        }
        if (JsonUtil.isNotValidJsonStr(studentDO.getConfigJson())) {
            return AjaxResult.fail("格式不是合法JSON字符，请重新输入。");
        }
        studentDO.setUpdateTime(new Date());
        return AjaxResult.toAjax(studentMapper.updateStudent(studentDO));
    }

    @Override
    public AjaxResult deleteStudentById(Long id) {
        return AjaxResult.toAjax(studentMapper.deleteStudentById(id));
    }

    @Override
    public AjaxResult deleteStudentByIds(Long[] ids) {
        return AjaxResult.toAjax(studentMapper.deleteStudentByIds(ids));
    }

}
